package cn.bdqn.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 发送邮件的服务
 */
@Service
public class EmailService {

    @Value("${send.email.username}")
    private String sendUsername;
    @Value("${send.email.code}")
    private String sendCode;

    /**
     * 发送邮件
     * @address 收件邮箱地址
     * @title 邮件标题
     * @text 邮件详情
     * @return
     */
    public boolean sending(String address,String title,String text){
        // 构建Properties对象
        Properties properties = new Properties();
        // 设置主机名（IP）
        properties.put("mail.smtp.host", "smtp.qq.com");
        // 设置端口号
        properties.put("mail.smtp.port", "25");
        // 发送服务器需要身份验证
        properties.put("mail.smtp.auth", "true");
        // 创建EmailSession
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //设置发送邮件的用户名和密码,这里password不是登录密码，而是授权码
                return new PasswordAuthentication(sendUsername, sendCode);
            }
        });
        // 构建Message对象
        Message message = new MimeMessage(session);
        try {
            // 设置发送邮件的QQ账户
            message.setFrom(new InternetAddress(sendUsername));
            // 设置接收邮件的QQ账户
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
            // 设置邮件标题
            message.setSubject(title);
            // 设置编码格式
            message.setContent(text, "text/html;charset=utf-8");
            // 发送邮件
            Transport.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
